<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item :label="v.name" :prop="v.prop" v-for="v in searchItems">
        <el-input v-if="v.type == 'input'" v-model="queryParams[v.prop]" :placeholder="'请输入' + v.name" clearable
          @keyup.enter="handleQuery" />
        <el-select v-else-if="v.type == 'select'" v-model="queryParams[v.prop]" clearable filterable
          :placeholder="'请输入' + v.name" @change="handleQuery">
          <el-option v-for="item in sel_option[v.option]" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['comlbs:agreement:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['comlbs:agreement:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['comlbs:agreement:export']">导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table highlight-current-row v-loading="loading" :data="agreementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column :label="v.name" align="left" :prop="v.prop" v-for="v in tableItems" :width="v.width">
        <template #default="scope">
          <dict-tag v-if="v.type == 'dict'" :options="sel_option[v.option]" :value="scope.row[v.prop]" />
          <span v-else>{{ scope.row[v.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['comlbs:agreement:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['comlbs:agreement:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改设备接入协议对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body class="sky-form">
      <el-form ref="agreementRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item v-for="v in updateItem" :key="v.prop" :label="v.name" :prop="v.prop">
          <el-input v-if="v.type == 'input'" v-model.trim="form[v.prop]"></el-input>
          <el-select v-else-if="v.type == 'select'" v-model="form[v.prop]" filterable clearable>
            <el-option v-for="item in sel_option[v.option]" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Agreement">
import { listAgreement, getAgreement, delAgreement, addAgreement, updateAgreement } from "@/api/comlbs/agreement";

const { proxy } = getCurrentInstance();

const agreementList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 15,
    agreementName: null,
    domain: null,
    ip: null,
    port: null,
    type: null,
    gmtCreate: null,
    gmtModified: null
  },
  rules: {
    agreementName: [
      { required: true, message: "请输入协议名称", trigger: "blur" },
      { required: true, message: "请输入协议名称", trigger: "change" },
      { min: 0, max: 30, message: "长度在0到30个字符", trigger: "blur" },
    ],
    domain: [
      { required: true, message: "请输入接入域名", trigger: "blur" },
      {
        validator: function (rule, value, callback) {
          let MyRegExp = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/;
          let judgeFn = new RegExp(/\s+/g);

          if (MyRegExp.test(value) == false) {
            callback(new Error("请输入合法的域名"));
          } else if (judgeFn.test(value)) {
            callback(new Error("内容包含有空格"));
          } else {
            //校验通过
            callback();
          }
        },
        trigger: "blur",
      },
      { required: true, message: "请输入接入域名", trigger: "change" },
    ],
    ip: [
      { required: true, message: "请输入接入ip", trigger: "blur" },
      {
        validator: function (rule, value, callback) {
          let MyRegExp = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/;
          if (MyRegExp.test(value) == false) {
            callback(new Error("请输入合法的ip地址"));
          } else {
            //校验通过
            callback();
          }
        },
        trigger: "blur",
      },
      { required: true, message: "请输入接入ip", trigger: "change" },
    ],
    port: [
      { required: true, message: "请输入接入端口号", trigger: "blur" },
      {
        validator: function (rule, value, callback) {
          let MyRegExp = /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
          if (MyRegExp.test(value) == false) {
            callback(new Error("请输入合法的端口号"));
          } else {
            //校验通过
            callback();
          }
        },
        trigger: "blur",
      },
      { required: true, message: "请输入接入端口号", trigger: "change" },
    ],
    type: [
      { required: true, message: "请选择类型", trigger: "change" },
    ]
  }
});
const searchItems = ref([
  { name: '协议名称', prop: "agreementName", type: 'input' },
  { name: '协议类型', prop: "type", option: 'protocolType', type: 'select' },
]);
const tableItems = ref([
  { name: '协议名称', prop: "agreementName" },
  { name: '接入域名', prop: "domain" },
  { name: '接入ip', prop: "ip" },
  { name: '接入端口号', prop: "port" },
  { name: '类型', prop: "type", option: 'protocolType', type: 'dict' },
  { name: '备注', prop: "remark" }
])
const updateItem = ref([
  { name: '协议名称', prop: 'agreementName', type: 'input' },
  { name: '接入域名', prop: 'domain', type: 'input' },
  { name: '接入ip', prop: 'ip', type: 'input' },
  { name: '接入端口号', prop: "port", type: 'input' },
  { name: '类型', prop: "type", option: 'protocolType', type: 'select' },
  { name: '备注', prop: 'remark', type: 'input' },
])
const sel_option = ref({});
let dictList = tableItems.value.filter(v => v.type == 'dict').map(v => v.option);
sel_option.value = proxy.useDict.apply(this, [...dictList]);
const { queryParams, form, rules } = toRefs(data);

/** 查询设备接入协议列表 */
function getList() {
  loading.value = true;
  listAgreement(queryParams.value).then(response => {
    agreementList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    agreementName: null,
    domain: null,
    ip: null,
    port: null,
    type: null,
    remark: null,
    gmtCreate: null,
    gmtModified: null
  };
  proxy.resetForm("agreementRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备接入协议";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getAgreement(_id).then(response => {
    form.value = response.data;
    form.value.type = response.data.type + '';
    open.value = true;
    title.value = "修改设备接入协议";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["agreementRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateAgreement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAgreement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  let length = row.id ? 1 : _ids.length
  proxy.$modal.confirm('是否确认删除这' + length + '项数据？').then(function () {
    return delAgreement(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comlbs/agreement/export', {
    ...queryParams.value
  }, `agreement_${new Date().getTime()}.xlsx`)
}

getList();
</script>
